﻿using System.Diagnostics;
using System.Text;

namespace JobTools.Helper
{
    public static class FileHelper
    {
        public static string Current_ProcessFullFilePath
        {
            get
            {
                return Process.GetCurrentProcess().MainModule.FileName;
            }
        }

        public static string Current_EnvironmentDirectory
        {
            get
            {
                return Environment.CurrentDirectory;
            }
        }

        public static string Current_IODirectory
        {
            get
            {
                return Directory.GetCurrentDirectory();
            }
        }

        public static string Current_DomainBaseDirectory
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory;
            }
        }

        public static string Current_DomainApplicationBase
        {
            get
            {
                return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            }
        }

        public static string Current_FormApplicationStartupPath
        {
            get
            {
                return Application.StartupPath;
            }
        }

        public static string Current_FormApplicationExecutablePath
        {
            get
            {
                return Application.ExecutablePath;
            }
        }

        public static void CreateDir(string dir, bool isWeb = false)
        {
            bool flag = dir.Length == 0;
            if (!flag)
            {
                if (isWeb)
                {
                    //bool flag2 = !Directory.Exists(HttpContext.Current.Server.MapPath(dir));
                    //if (flag2)
                    //{
                    //    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(dir));
                    //}
                }
                else
                {
                    bool flag3 = !Directory.Exists(dir);
                    if (flag3)
                    {
                        Directory.CreateDirectory(dir);
                    }
                }
            }
        }

        public static void DeleteDir(string dir)
        {
            bool flag = dir.Length == 0;
            if (!flag)
            {
                //bool flag2 = HttpContext.Current != null;
                //if (flag2)
                //{
                //    bool flag3 = Directory.Exists(HttpContext.Current.Server.MapPath(dir));
                //    if (flag3)
                //    {
                //        Directory.Delete(HttpContext.Current.Server.MapPath(dir), true);
                //    }
                //}
                //else
                //{
                bool flag4 = Directory.Exists(dir);
                if (flag4)
                {
                    Directory.Delete(dir, true);
                }
                //}
            }
        }

        public static bool FileExists(string file)
        {
            bool flag = false; //HttpContext.Current != null && File.Exists(HttpContext.Current.Server.MapPath(file));
            bool result;
            if (flag)
            {
                result = true;
            }
            else
            {
                bool flag2 = File.Exists(file);
                result = flag2;
            }
            return result;
        }

        public static string ReadFile(string file, Encoding encoding = null, bool isBinary = false)
        {
            string text = "";
            bool flag = encoding == null;
            if (flag)
            {
                encoding = Encoding.UTF8;
            }
            bool flag2 = !FileHelper.FileExists(file);
            string result;
            if (flag2)
            {
                result = "";
            }
            else
            {
                try
                {
                    string path = file;
                    //bool flag3 = HttpContext.Current != null;
                    //if (flag3)
                    //{
                    //    path = HttpContext.Current.Server.MapPath(file);
                    //}
                    bool flag4 = !isBinary;
                    if (flag4)
                    {
                        using (StreamReader streamReader = new StreamReader(path, encoding))
                        {
                            text = streamReader.ReadToEnd();
                            streamReader.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                result = text;
            }
            return result;
        }

        public static void SaveFile(string TxtStr, string tempDir)
        {
            FileHelper.SaveToFile(TxtStr, tempDir, false, false);
        }

        public static void CopyFile(string sFile, string tFile, bool overwrite)
        {
            //bool flag = HttpContext.Current != null;
            //if (flag)
            //{
            //    bool flag2 = File.Exists(HttpContext.Current.Server.MapPath(sFile));
            //    if (flag2)
            //    {
            //        File.Copy(HttpContext.Current.Server.MapPath(sFile), HttpContext.Current.Server.MapPath(tFile), overwrite);
            //    }
            //}
            //else
            //{
            bool flag3 = File.Exists(sFile);
            if (flag3)
            {
                File.Copy(sFile, tFile, overwrite);
            }
            //}
        }

        public static void DeleteFile(string file)
        {
            bool flag = file.Length == 0;
            if (!flag)
            {
                //bool flag2 = HttpContext.Current != null && File.Exists(HttpContext.Current.Server.MapPath(file));
                //if (flag2)
                //{
                //    File.Delete(HttpContext.Current.Server.MapPath(file));
                //}
                //else
                //{
                bool flag3 = File.Exists(file);
                if (flag3)
                {
                    File.Delete(file);
                }
                //}
            }
        }

        public static string GetFolderPath(string filePath)
        {
            return FileHelper.GetFolderPath(false, filePath);
        }

        public static string GetFolderPath(bool isUrl, string filePath)
        {
            string result;
            if (isUrl)
            {
                result = filePath.Substring(0, filePath.LastIndexOf("/") + 1);
            }
            else
            {
                result = filePath.Substring(0, filePath.LastIndexOf("\\") + 1);
            }
            return result;
        }

        public static string GetFileName(string filePath)
        {
            return FileHelper.GetFileName(false, filePath);
        }

        public static string GetFileName(bool isUrl, string filePath)
        {
            string result;
            if (isUrl)
            {
                result = filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - filePath.LastIndexOf("/") - 1);
            }
            else
            {
                result = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.Length - filePath.LastIndexOf("\\") - 1);
            }
            return result;
        }

        public static string GetFileExt(string filePath)
        {
            string text = Path.GetExtension(filePath);
            bool flag = text.StartsWith(".");
            if (flag)
            {
                text = text.Substring(1);
            }
            return text;
        }

        public static void CopyDir(string OldDir, string NewDir)
        {
            DirectoryInfo oldDirectory = new DirectoryInfo(OldDir);
            DirectoryInfo newDirectory = new DirectoryInfo(NewDir);
            FileHelper.CopyDir(oldDirectory, newDirectory);
        }

        private static void CopyDir(DirectoryInfo OldDirectory, DirectoryInfo NewDirectory)
        {
            string text = NewDirectory.FullName + "\\" + OldDirectory.Name;
            bool flag = !Directory.Exists(text);
            if (flag)
            {
                Directory.CreateDirectory(text);
            }
            FileInfo[] files = OldDirectory.GetFiles();
            FileInfo[] array = files;
            for (int i = 0; i < array.Length; i++)
            {
                FileInfo fileInfo = array[i];
                File.Copy(fileInfo.FullName, text + "\\" + fileInfo.Name, true);
            }
            DirectoryInfo[] directories = OldDirectory.GetDirectories();
            DirectoryInfo[] array2 = directories;
            for (int j = 0; j < array2.Length; j++)
            {
                DirectoryInfo oldDirectory = array2[j];
                DirectoryInfo newDirectory = new DirectoryInfo(text);
                FileHelper.CopyDir(oldDirectory, newDirectory);
            }
        }

        public static void DelDir(string OldDir)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(OldDir);
            directoryInfo.Delete(true);
        }

        public static void CopyAndDelDir(string OldDirectory, string NewDirectory)
        {
            FileHelper.CopyDir(OldDirectory, NewDirectory);
            FileHelper.DelDir(OldDirectory);
        }

        //public static bool DownloadFile(HttpRequest _Request, HttpResponse _Response, string _fullPath, long _speed)
        //{
        //    string fileName = FileHelper.GetFileName(false, _fullPath);
        //    bool result;
        //    try
        //    {
        //        FileStream fileStream = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        //        BinaryReader binaryReader = new BinaryReader(fileStream);
        //        try
        //        {
        //            _Response.AddHeader("Accept-Ranges", "bytes");
        //            _Response.Buffer = false;
        //            long length = fileStream.Length;
        //            long num = 0L;
        //            double num2 = 10240.0;
        //            int millisecondsTimeout = (int)Math.Floor(1000.0 * num2 / (double)_speed) + 1;
        //            bool flag = _Request.Headers["Range"] != null;
        //            if (flag)
        //            {
        //                _Response.StatusCode = 206;
        //                string[] array = _Request.Headers["Range"].Split(new char[]
        //                {
        //                    '=',
        //                    '-'
        //                });
        //                num = Convert.ToInt64(array[1]);
        //            }
        //            _Response.AddHeader("Content-Length", (length - num).ToString());
        //            _Response.AddHeader("Connection", "Keep-Alive");
        //            _Response.ContentType = "application/octet-stream";
        //            _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
        //            binaryReader.BaseStream.Seek(num, SeekOrigin.Begin);
        //            int num3 = (int)Math.Floor((double)(length - num) / num2) + 1;
        //            for (int i = 0; i < num3; i++)
        //            {
        //                bool isClientConnected = _Response.IsClientConnected;
        //                if (isClientConnected)
        //                {
        //                    _Response.BinaryWrite(binaryReader.ReadBytes(int.Parse(num2.ToString())));
        //                    Thread.Sleep(millisecondsTimeout);
        //                }
        //                else
        //                {
        //                    i = num3;
        //                }
        //            }
        //        }
        //        catch
        //        {
        //            result = false;
        //            return result;
        //        }
        //        finally
        //        {
        //            binaryReader.Close();
        //            fileStream.Close();
        //        }
        //    }
        //    catch
        //    {
        //        result = false;
        //        return result;
        //    }
        //    result = true;
        //    return result;
        //}

        public static string FileNameFilterSpecial(string strToFileName)
        {
            bool flag = string.Empty == strToFileName;
            string result;
            if (flag)
            {
                result = strToFileName;
            }
            else
            {
                string[] array = new string[]
                {
                    "?",
                    "<",
                    ">",
                    "\\",
                    "/",
                    ":",
                    "\"",
                    "|",
                    "*",
                    "&nbsp;",
                    "&quot;",
                    "&lt;",
                    "&gt;",
                    "#",
                    "+",
                    " "
                };
                for (int i = 0; i < array.Length; i++)
                {
                    strToFileName = strToFileName.Replace(array[i], "_");
                }
                result = strToFileName;
            }
            return result;
        }

        public static string GetPathWithSlash(string dirPath, bool createIfNotExists = false)
        {
            bool flag = !Directory.Exists(dirPath) & createIfNotExists;
            if (flag)
            {
                Directory.CreateDirectory(dirPath);
            }
            bool flag2 = dirPath.Trim().EndsWith("\\");
            string result;
            if (flag2)
            {
                result = dirPath.Trim();
            }
            else
            {
                result = dirPath.Trim() + "\\";
            }
            return result;
        }

        public static void SaveToFile(string cnt, string filePath, bool overWrite = false, bool saveInBinary = false)
        {
            string text = filePath.Substring(0, filePath.LastIndexOf("\\"));
            bool flag = text.Trim() != "";
            if (flag)
            {
                FileHelper.CreateDir(text, false);
            }
            bool flag2 = overWrite && File.Exists(filePath);
            if (flag2)
            {
                File.Delete(filePath);
            }
            bool flag3 = !saveInBinary;
            if (flag3)
            {
                using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                {
                    using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8))
                    {
                        streamWriter.WriteLine(cnt);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                    fileStream.Close();
                }
            }
            else
            {
                MemoryStream m = new MemoryStream(Encoding.UTF8.GetBytes(cnt));
                using (FileStream fileStream2 = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    m.WriteTo(fileStream2);
                    fileStream2.Close();
                }
            }
        }
    }
}
